﻿<script lang="ts" setup name="storeInbound">
import { ref, reactive, onMounted, nextTick } from "vue";
import { auth } from '/@/utils/authFunction';
import { ElMessage } from "element-plus";
import { downloadStreamFile } from "/@/utils/download";
import { useStoreMaterialsApi } from '/@/api/store/storeMaterials';
import { useStoreInboundApi } from '/@/api/store/storeInbound';
import { useUserInfo } from '/@/stores/userInfo';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';

// 组件导入
import StoreTypeTree from '/@/views/store/storeMaterials/component/storeTypeTree.vue';
import CartManager from '/@/views/store/components/CartManager.vue';
import printDialog from '/@/views/system/print/component/hiprint/preview.vue';
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import ImportData from "/@/components/table/importData.vue";

const storeMaterialsApi = useStoreMaterialsApi();
const storeInboundApi = useStoreInboundApi();
const userInfo = useUserInfo();
const printDialogRef = ref();
const cartManagerRef = ref();
const importDataRef = ref();
const storeTypeTreeRef = ref();

const state = reactive({
  exportLoading: false,
  tableLoading: false,
  stores: {},
  showAdvanceQueryUI: false,
  dropdownData: {} as any,
  selectData: [] as any[],
  storeTypeTreeData: [] as any[], // 物资分类树数据
  currentCategoryId: 0, // 当前选中的分类ID，0表示全部
  tableQueryParams: {} as any,
  tableParams: {
    page: 1,
    pageSize: 20,
    total: 0,
    field: 'createTime',
    order: 'descending',
    descStr: 'descending',
  },
  tableData: [],
  cartItems: [] as any[], // 购物车物品
});

// 页面加载时
onMounted(async () => {
  await loadStoreTypeTree();
  await handleQuery();
});

// 加载物资分类树数据
const loadStoreTypeTree = async () => {
  try {
    const data = (await storeMaterialsApi.getDropdownData(true).then((res) => res.data.result)) ?? {};
    console.log('API返回数据:', data);
    state.dropdownData.storeTypeId = data.pid || [];
    state.storeTypeTreeData = data.pid || [];
    console.log('树数据:', state.storeTypeTreeData);
  } catch (error) {
    console.error('加载物资分类树失败:', error);
    ElMessage.error('加载物资分类失败');
  }
};

// 分类节点点击事件
const handleCategoryChange = (node: any) => {
  const nodeId = node.id || node.value || 0;
  state.currentCategoryId = nodeId;
  state.tableParams.page = 1;
  if (nodeId === 0 || nodeId === '0') {
    delete state.tableQueryParams.storeTypeId;
  } else {
    state.tableQueryParams.storeTypeId = nodeId;
  }
  handleQuery();
};

// 查询操作
const handleQuery = async (params: any = {}) => {
  state.tableLoading = true;
  try {
    state.tableParams = Object.assign(state.tableParams, params);
    const queryParams = Object.assign({}, state.tableQueryParams, state.tableParams);
    const result = await storeMaterialsApi.page(queryParams).then((res) => res.data.result);
    state.tableParams.total = result?.total;
    state.tableData = result?.items ?? [];
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('查询失败');
  } finally {
    state.tableLoading = false;
  }
};

// 重置查询
const resetQuery = () => {
  state.tableQueryParams = {};
  state.currentCategoryId = 0;
  nextTick(() => {
    storeTypeTreeRef.value?.setCurrentKey(0);
  });
  handleQuery();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  state.tableParams.pageSize = val;
  state.tableParams.page = 1;
  handleQuery();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  state.tableParams.page = val;
  handleQuery();
};

// 列排序
const sortChange = async (column: any) => {
  state.tableParams.field = column.prop;
  state.tableParams.order = column.order;
  await handleQuery();
};

// 加入购物车
const addToCart = (row: any) => {
  // 入库操作不需要检查可用库存，因为入库是增加库存的操作
  
  // 检查是否已存在
  const existingIndex = state.cartItems.findIndex(item => item.id === row.id);
  if (existingIndex !== -1) {
    // 如果已存在，增加数量
    state.cartItems[existingIndex].requestQuantity += 1;
    ElMessage.success(`${row.name} 数量已增加 1 个`);
    return;
  }
  
  // 添加到购物车
  const cartItem = {
    ...row,
    requestQuantity: 1, // 默认申请数量为1
    remark: ''
  };
  
  state.cartItems.push(cartItem);
  ElMessage.success(`已将"${row.name}"添加到购物车`);
};

// 打开购物车
const openCart = () => {
  cartManagerRef.value?.openCart();
};

// 移除购物车物品
const removeFromCart = (index: number) => {
  state.cartItems.splice(index, 1);
  ElMessage.success('已移除物品');
};

// 清空购物车
const clearCart = () => {
  state.cartItems = [];
  ElMessage.success('购物车已清空');
};

// 生成申请号
const generateRequestNo = () => {
  const now = new Date();
  const dateTimeStr = now.toISOString().slice(0, 19).replace(/[-:T]/g, '').slice(0, 14);
  return `IN${dateTimeStr}`;
};

// 生成批次号
const generateBatchNo = () => {
  const now = new Date();
  const dateStr = now.toISOString().slice(0, 10).replace(/-/g, '');
  const timeStr = now.toTimeString().slice(0, 8).replace(/:/g, '');
  return `BATCH_${dateStr}_${timeStr}`;
};

// 提交购物车
const submitCart = async (items: any[], form: any) => {
  try {
    // 检查是否有用户信息
    if (!userInfo.userInfos?.id) {
      ElMessage.error('获取用户信息失败，请重新登录');
      return;
    }

    // 构建入库申请数据
    const batchNo = generateBatchNo();
    const requestTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
    
    const requests = items.map(item => ({
      batchNo: batchNo,
      requestNo: generateRequestNo(),
      storeTypeId: item.storeTypeId,
      storeTypeName: item.storeTypeDisplayName,
      materialId: item.id,
      materialName: item.name,
      materialPrice: item.price,
      quantity: item.requestQuantity,
      unit: item.unit,
      materialPriceTotal: item.price * item.requestQuantity,
      applicantId: userInfo.userInfos.id,
      applicantName: userInfo.userInfos.realName || userInfo.userInfos.name,
      applicantDept: userInfo.userInfos.orgName || '',
      receiverId: item.receiverId,
      receiverName: item.receiverName,
      receiverDept: item.receiverDept,
      requestTime: requestTime,
      expectedDate: item.expectedDate,
      statusNewOrChange: item.statusNewOrChange,
      remark: item.remark,
      approvalAction: 1, // 审批状态：待审核(Pending)
      confirmerId: form?.confirmerId || userInfo.userInfos.managerUserId, // 优先使用表单选择的确认人，fallback到直属主管
      confirmerName: form?.confirmerName || '', // 确认人名称
    }));
    
    // 调用后端API提交入库申请
    console.log('提交入库申请:', requests);
    
    // 使用Promise.all并发调用API提高性能
    const results = await Promise.allSettled(
      requests.map(request => storeInboundApi.add(request))
    );
    
    const successCount = results.filter(result => result.status === 'fulfilled').length;
    const failCount = results.filter(result => result.status === 'rejected').length;
    
    // 记录失败的请求
    results.forEach((result, index) => {
      if (result.status === 'rejected') {
        console.error('提交入库申请失败:', result.reason, requests[index]);
      }
    });
    
    // 显示结果
    if (failCount === 0) {
      ElMessage.success(`成功提交 ${successCount} 项入库申请`);
    } else if (successCount === 0) {
      ElMessage.error(`提交失败，所有 ${failCount} 项入库申请都未成功`);
      cartManagerRef.value?.resetSubmitting();
      return;
    } else {
      ElMessage.warning(`部分成功：成功 ${successCount} 项，失败 ${failCount} 项`);
    }
    
    cartManagerRef.value?.resetSubmitting();
    cartManagerRef.value?.handleClose();
    cartManagerRef.value?.resetForm();
    state.cartItems = [];
    
    // 刷新物资列表以更新库存信息
    await handleQuery();
    
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败');
    cartManagerRef.value?.resetSubmitting();
  }
};

// 导出数据
const exportStoreMaterialsCommand = async (command: string) => {
  try {
    state.exportLoading = true;
    let params;
    if (command === 'select') {
      params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map((u) => u.id) });
    } else if (command === 'current') {
      params = Object.assign({}, state.tableQueryParams, state.tableParams);
    } else if (command === 'all') {
      params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
    }
    await storeMaterialsApi.exportData(params).then((res) => downloadStreamFile(res));
  } finally {
    state.exportLoading = false;
  }
};
</script>
<template>
	<div class="store-inbound-container" v-loading="state.exportLoading">
		<splitpanes class="default-theme">
			<!-- 左侧物资分类树 -->
			<pane size="15">
				<StoreTypeTree ref="storeTypeTreeRef" :data="state.storeTypeTreeData" @node-click="handleCategoryChange" @refresh="loadStoreTypeTree" />
			</pane>

			<!-- 右侧物资信息表格 -->
			<pane size="80" style="overflow: auto">
				<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
					<el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
						<el-row>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
								<el-form-item label="关键字">
									<el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入模糊查询关键字" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
								<el-form-item label="物资名称">
									<el-input v-model="state.tableQueryParams.name" clearable placeholder="请输入物资名称" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
								<el-form-item label="状态">
									<g-sys-dict v-model="state.tableQueryParams.status" code="StatusEnum" render-as="select" placeholder="请选择状态" clearable filterable />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
								<el-form-item label="库存状态">
									<g-sys-dict v-model="state.tableQueryParams.stockStatus" code="StockStatusEnum" render-as="select" placeholder="请选择库存状态" clearable filterable />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
								<el-form-item>
									<el-button-group style="display: flex; align-items: center">
										<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'storeMaterials:page'" v-reclick="1000"> 查询 </el-button>
										<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
										<el-button icon="ele-ZoomIn" @click="() => (state.showAdvanceQueryUI = true)" v-if="!state.showAdvanceQueryUI" style="margin-left: 5px"> 高级查询 </el-button>
										<el-button icon="ele-ZoomOut" @click="() => (state.showAdvanceQueryUI = false)" v-if="state.showAdvanceQueryUI" style="margin-left: 5px"> 隐藏 </el-button>
										<el-button type="success" style="margin-left: 5px" icon="ele-ShoppingCart" @click="openCart" :disabled="state.cartItems.length === 0"> 购物车 ({{ state.cartItems.length }}) </el-button>
										<el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportStoreMaterialsCommand">
											<el-button type="primary" style="margin-left: 5px" icon="ele-FolderOpened" v-reclick="20000" v-auth="'storeMaterials:export'"> 导出 </el-button>
											<template #dropdown>
												<el-dropdown-menu>
													<el-dropdown-item command="select" :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
													<el-dropdown-item command="current">导出本页</el-dropdown-item>
													<el-dropdown-item command="all">导出全部</el-dropdown-item>
												</el-dropdown-menu>
											</template>
										</el-dropdown>
									</el-button-group>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-card>

				<el-card class="full-table" shadow="hover" style="margin-top: 5px">
					<el-table
						:data="state.tableData"
						@selection-change="
							(val: any[]) => {
								state.selectData = val;
							}
						"
						style="width: 100%"
						v-loading="state.tableLoading"
						tooltip-effect="light"
						row-key="id"
						@sort-change="sortChange"
						border
					>
						<el-table-column type="selection" width="40" align="center" fixed="left" v-if="auth('storeMaterials:export')" />
						<el-table-column type="index" label="序号" width="55" align="center" fixed="left" />
						<el-table-column prop="storeTypeId" label="分类" width="150" fixed="left" :formatter="(row: any) => row.storeTypeDisplayName" show-overflow-tooltip />
						<el-table-column prop="name" label="物资名称" width="200" fixed="left" show-overflow-tooltip />
						<el-table-column prop="unit" label="单位" show-overflow-tooltip />
						<el-table-column prop="price" label="单价" show-overflow-tooltip />
						<el-table-column prop="minStock" label="最小库存" show-overflow-tooltip />
						<el-table-column prop="maxStock" label="最大库存" show-overflow-tooltip />
						<el-table-column prop="orderNo" label="排序" sortable="custom" show-overflow-tooltip />
						<el-table-column prop="status" label="状态" show-overflow-tooltip>
							<template #default="scope">
								<g-sys-dict v-model="scope.row.status" code="StatusEnum" />
							</template>
						</el-table-column>
						<el-table-column prop="currentStock" label="库存数量" show-overflow-tooltip />
						<el-table-column prop="availableStock" label="可用库存" fixed="left" show-overflow-tooltip />
						<el-table-column prop="reservedStock" label="申请库存" show-overflow-tooltip />
						<el-table-column prop="inTransitStock" label="入库库存" show-overflow-tooltip />
						<el-table-column prop="stockStatus" label="库存状态" fixed="left" show-overflow-tooltip>
							<template #default="scope">
								<g-sys-dict v-model="scope.row.stockStatus" code="StockStatusEnum" />
							</template>
						</el-table-column>
						<el-table-column prop="lastStockUpdateTime" label="更新时间" show-overflow-tooltip />
						<el-table-column prop="remark" label="备注" show-overflow-tooltip />
						<el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip>
							<template #default="scope">
								<ModifyRecord :data="scope.row" />
							</template>
						</el-table-column>
						<el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip>
							<template #default="scope">
								<el-button icon="ele-ShoppingCart" size="small" text type="primary" @click="addToCart(scope.row)"> 加入购物车 </el-button>
							</template>
						</el-table-column>
					</el-table>

					<el-pagination
						v-model:currentPage="state.tableParams.page"
						v-model:page-size="state.tableParams.pageSize"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						layout="total, sizes, prev, pager, next, jumper"
						:page-sizes="[10, 20, 50, 100, 200, 500]"
						:total="state.tableParams.total"
						size="small"
						background
					/>
				</el-card>
			</pane>
		</splitpanes>

		<!-- 购物车组件 -->
		<CartManager 
			ref="cartManagerRef" 
			cart-type="inbound" 
			:cart-items="state.cartItems" 
			@submit-cart="submitCart" 
			@remove-item="removeFromCart" 
			@clear-cart="clearCart" 
			@close="() => {}" 
		/>

		<!-- 对话框组件 -->
		<ImportData ref="importDataRef" :import="storeMaterialsApi.importData" :download="storeMaterialsApi.downloadTemplate" v-auth="'storeMaterials:import'" @refresh="handleQuery" />
		<printDialog ref="printDialogRef" :title="'打印物资信息表'" @reloadTable="handleQuery" />
	</div>
</template>
<style scoped>
.store-inbound-container {
	height: calc(100vh - 84px);
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}

:deep(.splitpanes__pane) {
	overflow: hidden;
}

:deep(.splitpanes__splitter) {
	background-color: var(--el-border-color-light);
	position: relative;
	opacity: 0.7;
}

:deep(.splitpanes__splitter:hover) {
	opacity: 1;
	background-color: var(--el-color-primary);
}
</style>